import {RouteProp} from '@react-navigation/native';
import React, {useEffect, useState, useMemo, useRef} from 'react';
import {View, Text, StyleSheet, Easing, Animated} from 'react-native';
import {ModalStackNavigation, ModalStackParamList} from '@/navigator/index';
import {useDidMount, viewportWidth} from '@/utils/index';
import {RootState} from '@/models/index';
import {connect, ConnectedProps} from 'react-redux';
import Touchable from '@/components/Touchable';
import Icon from '@/assets/iconfont/index';
import PlaySlider from './PlaySlider';
// import Animated from 'react-native-reanimated';
import LinearGradient from 'react-native-linear-gradient';
import Barrage from './Barrage/index';

// mock数据
const data: string[] = [
  '最灵繁的人也看不见自己的背脊',
  '朝闻道，夕死可矣',
  '阅读是人类进步的阶梯',
  '内外相应，言行相称',
  '人的一生是短的',
  '抛弃时间的人，时间也抛弃他',
  '自信在于沉稳',
  '过犹不及',
  '开卷有益',
  '有志者事竟成',
  '合理安排时间，就等于节约时间',
  '成功源于不懈的努力',
];

const randomIndex = (length: number) => {
  return Math.floor(Math.random() * length);
};
export interface Message {
  id: number;
  title: string;
}

const getText = () => {
  return data[randomIndex(data.length)];
};

const mapStateToProps = ({player}: RootState) => {
  return {
    player: player,
  };
};

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
  navigation: ModalStackNavigation;
  route: RouteProp<ModalStackParamList, 'Detail'>; //获取路由相关参数
}
// 图片宽度
const IMAGE_WIDTH = 180;
// 计算图片paddingTop
const PADDING_TOP = (viewportWidth - IMAGE_WIDTH) / 2;
//
const SCALE = viewportWidth / IMAGE_WIDTH;

const Detail: React.FC<IProps> = props => {
  const {navigation, dispatch, route, player} = props;
  const {playState, title, previousId, nextId, thumbnailUrl, id} = player;
  const [barrage, setBarrage] = useState(false);
  const createBarrageRef: any = useRef();
  const [BarrageData, setBarrageData] = useState<Message[]>([]);
  const anim = useMemo(() => new Animated.Value(1), []);
  const [timer, setTimer] = useState<any>(null);
  useEffect(() => {
    createBarrageRef.current = barrage; //解决useState在定时器中闭包问题
  }, [barrage]);
  useDidMount(() => {
    createBarrageRef.current = barrage;
    if (route.params && route.params.id !== id) {
      dispatch({
        type: 'player/fetchShow',
        payload: {
          id: route.params.id,
        },
      });
    } else {
      dispatch({
        type: 'player/play',
      });
    }
    addBarrage();
    return () => {
      clearTimeout(timer);
    };
  });
  useEffect(() => {
    navigation.setOptions({
      headerTitle: title,
    });
  }, [navigation, title]);
  const toggle = () => {
    dispatch({
      type: playState === 'playing' ? 'player/pause' : 'player/play',
    });
  };
  const previous = () => {
    dispatch({
      type: 'player/previous',
    });
  };
  const next = () => {
    dispatch({
      type: 'player/next',
    });
  };
  const barrageBtnClick = () => {
    setBarrage(!barrage);
    // 开始动画
    Animated.timing(anim, {
      toValue: !barrage ? SCALE : 1, //动画比例
      duration: 100, //动画时间
      easing: Easing.linear, //动画类型线性的渐变函数
      useNativeDriver: true, //使用原生动画
    }).start();
  };

  const addBarrage = () => {
    setTimer(
      setInterval(() => {
        const sign = createBarrageRef.current;
        if (sign) {
          const id = Date.now();
          const title = getText();
          setBarrageData([{id, title}]);
        }
      }, 500),
    );
  };

  return (
    <View style={styles.container}>
      <View style={styles.imageView}>
        <Animated.Image
          source={{uri: thumbnailUrl}}
          style={[
            styles.image,
            {transform: [{scale: anim}], borderRadius: barrage ? 0 : 8},
          ]}
        />
      </View>
      {barrage && (
        <>
          <LinearGradient
            colors={['rgba(128, 104, 102, 0.5)', '#807c66']}
            style={styles.linear}
          />
          <Barrage data={BarrageData} maxTrack={5} style={{top: PADDING_TOP}} />
        </>
      )}
      <Touchable style={styles.barrageBtn} onPress={barrageBtnClick}>
        <Text style={styles.barrageText}>弹幕</Text>
      </Touchable>
      <PlaySlider />
      <View style={styles.control}>
        <Touchable
          onPress={previous}
          style={styles.button}
          disabled={!previousId}>
          <Icon name="icon-shangyishou" size={30} color="#FFF" />
        </Touchable>
        <Touchable onPress={toggle} style={styles.button}>
          <Icon
            name={playState === 'playing' ? 'icon-pause' : 'icon-bofang'}
            size={40}
            color="#FFF"
          />
        </Touchable>
        <Touchable onPress={next} style={styles.button} disabled={!nextId}>
          <Icon name="icon-xiayishou" size={30} color="#FFF" />
        </Touchable>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingTop: PADDING_TOP,
  },
  imageView: {
    alignItems: 'center',
    height: IMAGE_WIDTH,
  },
  image: {
    width: IMAGE_WIDTH,
    height: IMAGE_WIDTH,
    borderRadius: 8,
    backgroundColor: '#ccc',
  },
  linear: {
    position: 'absolute',
    top: 0,
    height: viewportWidth,
    width: viewportWidth,
  },
  barrageBtn: {
    height: 20,
    width: 40,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
    borderColor: '#FFF',
    borderWidth: StyleSheet.hairlineWidth,
    marginLeft: 10,
  },
  barrageText: {
    color: '#FFF',
  },
  control: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginVertical: 15,
    marginHorizontal: 90,
  },
  button: {
    marginHorizontal: 10,
  },
});

export default connector(Detail);
